package com.systop.dao;

import com.systop.entity.Notice;
import com.systop.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

import static com.systop.util.JdbcUtil.getConnection;

public class NoticeDao {

    public int add(Notice notice){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int i = 0;
        // 获取链接
        try {
            conn = getConnection();
            String sql = "INSERT INTO t_notice(title,content,pushtime,createtime)VALUES(?,?,?,?)";
            // 运行sql 代码
            pstmt = conn.prepareStatement(sql);
            // 传递参数
            pstmt.setString(1, notice.getTitle());
            pstmt.setString(2, notice.getContent());
            pstmt.setDate(3,new java.sql.Date(notice.getPushTime().getTime()));
            pstmt.setDate(4,new java.sql.Date(new Date().getTime()));
            // 执行代码,获取结果集
            i = pstmt.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstmt, rs);
        }
        return i;
    }


    public  ArrayList<Notice> findAll(){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList<Notice> noticeList = new ArrayList<Notice>();
        // 获取链接
        try {
            conn = getConnection();
            String sql ="select * from t_notice";
            // 运行sql 代码
            pstmt = conn.prepareStatement(sql);
            // 执行代码,获取结果集
            rs = pstmt.executeQuery();
            while (rs.next()) {
                Notice notice = new Notice();

                int id = rs.getInt("id");
                String title = rs.getString("title");
                String content = rs.getString("content");
                Date pushtime = rs.getDate("pushtime");
                Date createtime = rs.getDate("createtime");
                notice.setId(id);
                notice.setTitle(title);
                notice.setContent(content);
                notice.setPushTime(pushtime);
                notice.setCreateTime(createtime);
                noticeList.add(notice);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstmt, rs);
        }

        return noticeList;
    }

}
